package com.util.memcached;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.danga.MemCached.MemCachedClient;

@Component
public class MemcachedUtil implements CacheUtil {
	
	private static final Logger logger = Logger.getLogger(MemcachedUtil.class);
	@Autowired
	private MemCachedClient memcachedClient;
	
	@Override
	public boolean delete(String key) {
		return memcachedClient.delete(key);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(String key) {
		try {
			return (T) memcachedClient.get(key);
		} catch (RuntimeException e) {
			logger.warn("Get object from memcached fail,key is " + key, e);
			return null;
		}
	}

	@Override
	public boolean keyExists(String key) {
		return memcachedClient.keyExists(key);
	}

	@Override
	public boolean set(String key, Object value, int expiredTime) {
		if(expiredTime>0){
			Date expiry = new Date(System.currentTimeMillis() + expiredTime * 60 * 1000);
			return memcachedClient.set(key,value,expiry);
		}
		return memcachedClient.set(key,value);
	}

	@Override
	public boolean set(String key, Object value) {
		return memcachedClient.set(key,value);
	}

	@Override
	public boolean deleteAll() {
		return memcachedClient.flushAll();
	}
	@Override
	public Map<String, String> getAllItems() {
		Map<String, String> resultMap = new HashMap<String, String>();
		Map<String, Map<String, String>> items = memcachedClient.statsItems();
		for (Iterator<String> itemIt = items.keySet().iterator(); itemIt.hasNext();) {
		    String itemKey = itemIt.next();
		    Map<String, String> maps = items.get(itemKey);
		    for (Iterator<String> mapsIt = maps.keySet().iterator(); mapsIt.hasNext();) {
		        String mapsKey = mapsIt.next();
		        String mapsValue = maps.get(mapsKey);
		        if (mapsKey.endsWith("number")) {//memcached key 类型  item_str:integer:number_str
		            String[] arr = mapsKey.split(":");
		            int slabNumber = Integer.valueOf(arr[1].trim());
		            int limit = Integer.valueOf(mapsValue.trim());
		            Map<String, Map<String, String>> dumpMaps = memcachedClient.statsCacheDump(slabNumber, limit);
		            for (Iterator<String> dumpIt = dumpMaps.keySet().iterator(); dumpIt.hasNext();) {
		                String dumpKey = dumpIt.next();
		                Map<String, String> allMap = dumpMaps.get(dumpKey);
		                resultMap.putAll(allMap);
		            }
		        }
		    }
		}
		return resultMap;
	}
}
